import React, { useState, useEffect, useRef } from 'react';
import { Table, Spin, message, Input, Button, Modal, Form, InputNumber, Space, Tooltip, Popconfirm } from 'antd';
import { LeftOutlined, RightOutlined, PlusOutlined, ThunderboltOutlined, DeleteOutlined, SearchOutlined, EditOutlined } from '@ant-design/icons';
import axios from 'axios';
import { API_BASE_URL } from '../config';

// 特征映射组件的样式
const featureMappingStyles = `
  .feature-mapping-container {
    height: 100%;
    background-color: #fff;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .data-table {
    width: 100%;
  }
  
  .table-row-normal-height td {
    padding: 16px 8px;
  }
  
  .table-row-compact-height td {
    padding: 8px;
  }
  
  .compact-table .ant-table-thead > tr > th {
    padding: 8px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-top: 1px solid #e8e8e8;
    background: #fff;
  }
  
  .mapping-weight {
    font-weight: 500;
    color: #1766a3;
  }
  
  .table-header-actions {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
  }

  .feature-select-icon {
    color: #1766a3;
    cursor: pointer;
    margin-left: 8px;
  }
  
  .feature-select-icon:hover {
    color: #0a4b8c;
  }

  .input-with-icon {
    display: flex;
    align-items: center;
  }

  .feature-row {
    cursor: pointer;
  }
  
  .feature-row:hover {
    background-color: #f5f5f5;
  }
  
  /* 添加分页样式，确保页码正确显示 */
  .ant-pagination {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    color: rgba(0, 0, 0, 0.85);
    font-size: 14px;
    line-height: 1.5715;
    list-style: none;
    display: flex;
    align-items: center;
  }
  
  .ant-pagination-item {
    display: inline-flex;
    justify-content: center;
    align-items: center;
    min-width: 32px;
    height: 32px;
    margin-right: 8px;
    font-family: Arial;
    line-height: 30px;
    text-align: center;
    vertical-align: middle;
    list-style: none;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 2px;
    outline: 0;
    cursor: pointer;
    user-select: none;
  }
  
  .ant-pagination-item a {
    display: block;
    width: 100%;
    height: 100%;
    padding: 0 6px;
    color: rgba(0, 0, 0, 0.85);
    transition: none;
    text-decoration: none;
  }
  
  .ant-pagination-item-active {
    font-weight: 500;
    background: #fff;
    border-color: #1766a3;
  }
  
  .ant-pagination-item-active a {
    color: #1766a3;
  }

  /* 自定义的feature-pagination类 */
  .feature-pagination .ant-pagination-item {
    background-color: #fff;
    border: 1px solid #d9d9d9;
  }
  
  .feature-pagination .ant-pagination-item a {
    color: rgba(0, 0, 0, 0.85);
  }
  
  .feature-pagination .ant-pagination-item-active {
    border-color: #1766a3;
    background-color: #fff;
  }
  
  .feature-pagination .ant-pagination-item-active a {
    color: #1766a3;
  }

  @media (max-width: 576px) {
    .feature-mapping-container {
      margin: 0;
      border-radius: 0;
    }
  }
`;

// 特征映射列表组件
const FeatureMapping = () => {
  const [loading, setLoading] = useState(false);
  const [mappingList, setMappingList] = useState([]);
  const [allMappings, setAllMappings] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [isMobile, setIsMobile] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isProductFeatureModalVisible, setIsProductFeatureModalVisible] = useState(false);
  const [isTemplateFeatureModalVisible, setIsTemplateFeatureModalVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [currentEditMapping, setCurrentEditMapping] = useState(null);
  const [productFeatures, setProductFeatures] = useState([]);
  const [templateFeatures, setTemplateFeatures] = useState([]);
  const [productFeatureLoading, setProductFeatureLoading] = useState(false);
  const [templateFeatureLoading, setTemplateFeatureLoading] = useState(false);
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const inputRef = useRef(null);
  const [productSearchText, setProductSearchText] = useState('');
  const [templateSearchText, setTemplateSearchText] = useState('');
  const [filteredProductFeatures, setFilteredProductFeatures] = useState([]);
  const [filteredTemplateFeatures, setFilteredTemplateFeatures] = useState([]);

  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 576);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 获取特征映射列表
  useEffect(() => {
    fetchFeatureMappings();
  }, []);

  // 更新当前页数据
  useEffect(() => {
    if (allMappings.length > 0) {
      updatePageData(allMappings, currentPage);
    }
  }, [currentPage, pageSize, allMappings]);

  const fetchFeatureMappings = async () => {
    setLoading(true);
    try {
      // 获取特征映射列表
      const response = await axios.get(`${API_BASE_URL}/api/feature_mappings`);
      
      if (response.data && response.data.code === 200) {
        console.log('特征映射列表:', response.data.data);
        // 保存所有映射数据
        const items = response.data.data.items || [];
        setAllMappings(items);
        
        // 计算总数
        const total = items.length;
        setPagination({
          ...pagination,
          total: total
        });
        
        // 手动实现分页
        updatePageData(items, currentPage);
      } else {
        message.error('获取特征映射列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取特征映射列表错误:', error);
      message.error('获取特征映射列表失败: ' + (error.message || '网络错误'));
    } finally {
      setLoading(false);
    }
  };

  // 获取产品特征列表
  const fetchProductFeatures = async () => {
    setProductFeatureLoading(true);
    try {
      // 获取产品特征定义列表
      const response = await axios.get(`${API_BASE_URL}/api/product_feature_value`);
      
      if (response.data && response.data.code === 200) {
        console.log('产品特征列表:', response.data.data);
        const items = response.data.data.items || [];
        
        // 获取特征详细信息
        const featureIds = items.map(item => item.feature_id);
        const featuresWithDetails = await getFeatureDetails(items, featureIds);
        
        setProductFeatures(featuresWithDetails);
        setFilteredProductFeatures(featuresWithDetails);
      } else {
        message.error('获取产品特征列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取产品特征列表错误:', error);
      message.error('获取产品特征列表失败: ' + (error.message || '网络错误'));
    } finally {
      setProductFeatureLoading(false);
    }
  };

  // 获取模板特征列表
  const fetchTemplateFeatures = async () => {
    setTemplateFeatureLoading(true);
    try {
      // 获取模板特征定义列表
      const response = await axios.get(`${API_BASE_URL}/api/template_feature_value`);
      
      if (response.data && response.data.code === 200) {
        console.log('模板特征列表:', response.data.data);
        const items = response.data.data.items || [];
        
        // 获取特征详细信息
        const featureIds = items.map(item => item.feature_id);
        const featuresWithDetails = await getFeatureDetails(items, featureIds);
        
        setTemplateFeatures(featuresWithDetails);
        setFilteredTemplateFeatures(featuresWithDetails);
      } else {
        message.error('获取模板特征列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取模板特征列表错误:', error);
      message.error('获取模板特征列表失败: ' + (error.message || '网络错误'));
    } finally {
      setTemplateFeatureLoading(false);
    }
  };

  // 获取特征详细信息
  const getFeatureDetails = async (features, featureIds) => {
    if (!featureIds || featureIds.length === 0) return features;
    
    const detailsMap = {};
    const uniqueIds = [...new Set(featureIds)]; // 去重
    
    try {
      // 并行获取所有特征详情
      const requests = uniqueIds.map(id => 
        axios.get(`${API_BASE_URL}/api/feature_definition/${id}`)
      );
      
      const responses = await Promise.allSettled(requests);
      
      responses.forEach((response, index) => {
        if (response.status === 'fulfilled' && response.value.data && response.value.data.code === 200) {
          const feature = response.value.data.data;
          if (feature) {
            detailsMap[feature.id] = feature;
          }
        }
      });
      
      // 将详细信息合并到原特征对象中
      return features.map(feature => {
        const details = detailsMap[feature.feature_id] || {};
        return {
          ...feature,
          feature_name: details.feature_name || '未命名特征',
          feature_type: details.feature_type,
          data_type: details.data_type,
          description: details.description
        };
      });
    } catch (error) {
      console.error('获取特征详情错误:', error);
      return features; // 出错时返回原数据
    }
  };

  // 手动分页处理
  const updatePageData = (data, page) => {
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const currentPageData = data.slice(startIndex, endIndex);
    setMappingList(currentPageData);
  };

  // 处理页码变化
  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  // 处理页码输入
  const handlePageInputChange = (e) => {
    const value = parseInt(e.target.value, 10);
    if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
      setCurrentPage(value);
    }
  };

  // 处理页码输入框按键事件
  const handlePageInputKeyPress = (e) => {
    if (e.key === 'Enter') {
      const value = parseInt(e.target.value, 10);
      if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
        setCurrentPage(value);
      }
    }
  };

  // 前一页
  const goPrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  // 后一页
  const goNextPage = () => {
    if (currentPage < Math.ceil(pagination.total / pageSize)) {
      setCurrentPage(currentPage + 1);
    }
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '-';
    
    try {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      });
    } catch (e) {
      return dateString;
    }
  };

  // 显示添加映射模态框
  const showAddModal = () => {
    form.resetFields();
    setIsModalVisible(true);
  };

  // 处理添加映射提交
  const handleAddMapping = async () => {
    try {
      const values = await form.validateFields();
      console.log('添加映射:', values);
      
      setLoading(true);
      try {
        const response = await axios.post(`${API_BASE_URL}/api/feature_mappings`, {
          product_feature_id: values.product_feature_id,
          template_feature_id: values.template_feature_id,
          mapping_weight: values.mapping_weight
        });
        
        if (response.data && (response.data.code === 200 || response.data.code === 201)) {
          message.success('特征映射创建成功');
          setIsModalVisible(false);
          fetchFeatureMappings(); // 重新加载数据
        } else {
          message.error('创建特征映射失败: ' + (response.data.message || '未知错误'));
        }
      } catch (error) {
        console.error('创建特征映射错误:', error);
        message.error('创建特征映射失败: ' + (error.message || '网络错误'));
      } finally {
        setLoading(false);
      }
    } catch (errorInfo) {
      console.log('表单验证失败:', errorInfo);
    }
  };

  // 处理取消添加
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  // 打开产品特征选择模态框
  const showProductFeatureModal = () => {
    fetchProductFeatures();
    setProductSearchText('');
    setIsProductFeatureModalVisible(true);
  };

  // 打开模板特征选择模态框
  const showTemplateFeatureModal = () => {
    fetchTemplateFeatures();
    setTemplateSearchText('');
    setIsTemplateFeatureModalVisible(true);
  };

  // 处理产品特征选择
  const handleProductFeatureSelect = (feature) => {
    form.setFieldsValue({
      product_feature_id: feature.feature_id,
    });
    setIsProductFeatureModalVisible(false);
  };

  // 处理模板特征选择
  const handleTemplateFeatureSelect = (feature) => {
    form.setFieldsValue({
      template_feature_id: feature.feature_id,
    });
    setIsTemplateFeatureModalVisible(false);
  };

  // 自动创建特征映射
  const handleAutoCreateMapping = async () => {
    setLoading(true);
    try {
      const response = await axios.post(`${API_BASE_URL}/api/feature_mappings/auto_create`);
      
      if (response.data && response.data.code === 200) {
        const { created_count, updated_count } = response.data.data;
        message.success(`自动创建成功，新建${created_count}个映射，更新${updated_count}个映射`);
        fetchFeatureMappings(); // 重新加载数据
      } else {
        message.error('自动创建特征映射失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('自动创建特征映射错误:', error);
      message.error('自动创建特征映射失败: ' + (error.message || '网络错误'));
    } finally {
      setLoading(false);
    }
  };

  // 删除特征映射
  const handleDeleteMapping = async (id) => {
    setLoading(true);
    try {
      const response = await axios.delete(`${API_BASE_URL}/api/feature_mappings/${id}`);
      
      if (response.data && response.data.code === 200) {
        message.success('特征映射删除成功');
        fetchFeatureMappings(); // 重新加载数据
      } else {
        message.error('删除特征映射失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('删除特征映射错误:', error);
      message.error('删除特征映射失败: ' + (error.message || '网络错误'));
    } finally {
      setLoading(false);
    }
  };

  // 显示编辑映射模态框
  const showEditModal = (record) => {
    setCurrentEditMapping(record);
    editForm.setFieldsValue({
      mapping_weight: record.mapping_weight
    });
    setIsEditModalVisible(true);
  };

  // 处理编辑映射提交
  const handleEditMapping = async () => {
    if (!currentEditMapping) return;
    
    try {
      const values = await editForm.validateFields();
      console.log('编辑映射:', values);
      
      setLoading(true);
      try {
        const response = await axios.put(`${API_BASE_URL}/api/feature_mappings/${currentEditMapping.id}`, {
          mapping_weight: values.mapping_weight
        });
        
        if (response.data && response.data.code === 200) {
          message.success('特征映射更新成功');
          setIsEditModalVisible(false);
          fetchFeatureMappings(); // 重新加载数据
        } else {
          message.error('更新特征映射失败: ' + (response.data.message || '未知错误'));
        }
      } catch (error) {
        console.error('更新特征映射错误:', error);
        message.error('更新特征映射失败: ' + (error.message || '网络错误'));
      } finally {
        setLoading(false);
      }
    } catch (errorInfo) {
      console.log('表单验证失败:', errorInfo);
    }
  };

  // 取消编辑映射
  const handleEditCancel = () => {
    setIsEditModalVisible(false);
    setCurrentEditMapping(null);
  };

  // 产品特征列表列定义
  const productFeatureColumns = [
    {
      title: '特征ID',
      dataIndex: 'feature_id',
      key: 'feature_id',
      align: 'center',
    },
    {
      title: '特征名称',
      dataIndex: 'feature_name',
      key: 'feature_name',
      align: 'left',
    },
    {
      title: '特征类型',
      dataIndex: 'feature_type',
      key: 'feature_type',
      align: 'center',
    },
    {
      title: '特征值',
      dataIndex: 'feature_value',
      key: 'feature_value',
      align: 'center',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      align: 'left',
      ellipsis: true,
    }
  ];

  // 模板特征列表列定义
  const templateFeatureColumns = [
    {
      title: '特征ID',
      dataIndex: 'feature_id',
      key: 'feature_id',
      align: 'center',
    },
    {
      title: '特征名称',
      dataIndex: 'feature_name',
      key: 'feature_name',
      align: 'left',
    },
    {
      title: '特征类型',
      dataIndex: 'feature_type',
      key: 'feature_type',
      align: 'center',
    },
    {
      title: '特征值',
      dataIndex: 'feature_value',
      key: 'feature_value',
      align: 'center',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      align: 'left',
      ellipsis: true,
    }
  ];

  // 获取表格列定义
  const getColumns = () => {
    const baseColumns = [
      {
        title: '产品特征名称',
        dataIndex: 'product_feature_name',
        key: 'product_feature_name',
        align: 'left',
        ellipsis: true,
        render: (text) => <span>{text || '-'}</span>
      },
      {
        title: '模板特征名称',
        dataIndex: 'template_feature_name',
        key: 'template_feature_name',
        align: 'left',
        ellipsis: true,
        render: (text) => <span>{text || '-'}</span>
      },
      {
        title: '映射权重',
        dataIndex: 'mapping_weight',
        key: 'mapping_weight',
        align: 'center',
        ellipsis: true,
        render: (text) => <span className="mapping-weight">{text || '1.0'}</span>
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        align: 'center',
        ellipsis: true,
        render: (text) => <span>{formatDate(text)}</span>
      },
      {
        title: '更新时间',
        dataIndex: 'update_time',
        key: 'update_time',
        align: 'center',
        ellipsis: true,
        render: (text) => <span>{formatDate(text)}</span>
      },
      {
        title: '操作',
        key: 'action',
        align: 'center',
        render: (_, record) => (
          <Space size="small">
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              onClick={() => showEditModal(record)}
              title="修改权重"
            />
            <Popconfirm
              title="确定要删除此特征映射吗?"
              onConfirm={() => handleDeleteMapping(record.id)}
              okText="是"
              cancelText="否"
            >
              <Button type="text" danger icon={<DeleteOutlined />} />
            </Popconfirm>
          </Space>
        ),
      }
    ];
    
    // 移动端只显示核心列
    if (isMobile) {
      return baseColumns.filter(column => 
        ['product_feature_name', 'template_feature_name', 'mapping_weight', 'action'].includes(column.key)
      );
    }
    
    return baseColumns;
  };

  // 获取行样式
  const getRowClassName = () => {
    if (mappingList.length >= 10 || isMobile) {
      return "table-row-compact-height";
    }
    return "table-row-normal-height";
  };

  // 自定义分页样式
  const customPaginationStyle = {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '16px',
    borderTop: '1px solid #e8e8e8',
    background: '#fff'
  };

  // 搜索产品特征
  const handleProductFeatureSearch = (e) => {
    const value = e.target.value;
    setProductSearchText(value);
    
    if (!value) {
      setFilteredProductFeatures(productFeatures);
      return;
    }
    
    const filteredData = productFeatures.filter(feature => 
      (feature.feature_id && feature.feature_id.toString().includes(value)) ||
      (feature.feature_name && feature.feature_name.toLowerCase().includes(value.toLowerCase())) ||
      (feature.feature_value && feature.feature_value.toString().toLowerCase().includes(value.toLowerCase())) ||
      (feature.description && feature.description.toLowerCase().includes(value.toLowerCase()))
    );
    
    setFilteredProductFeatures(filteredData);
  };

  // 搜索模板特征
  const handleTemplateFeatureSearch = (e) => {
    const value = e.target.value;
    setTemplateSearchText(value);
    
    if (!value) {
      setFilteredTemplateFeatures(templateFeatures);
      return;
    }
    
    const filteredData = templateFeatures.filter(feature => 
      (feature.feature_id && feature.feature_id.toString().includes(value)) ||
      (feature.feature_name && feature.feature_name.toLowerCase().includes(value.toLowerCase())) ||
      (feature.feature_value && feature.feature_value.toString().toLowerCase().includes(value.toLowerCase())) ||
      (feature.description && feature.description.toLowerCase().includes(value.toLowerCase()))
    );
    
    setFilteredTemplateFeatures(filteredData);
  };

  // 获取选中的产品特征名称
  const getSelectedProductFeatureName = () => {
    try {
      if (!isModalVisible) return '';
    const featureId = form.getFieldValue('product_feature_id');
    if (!featureId) return '';
    
    const feature = productFeatures.find(item => item.feature_id === featureId);
    return feature ? feature.feature_name : '';
    } catch (error) {
      return '';
    }
  };

  // 获取选中的模板特征名称
  const getSelectedTemplateFeatureName = () => {
    try {
      if (!isModalVisible) return '';
    const featureId = form.getFieldValue('template_feature_id');
    if (!featureId) return '';
    
    const feature = templateFeatures.find(item => item.feature_id === featureId);
    return feature ? feature.feature_name : '';
    } catch (error) {
      return '';
    }
  };

  // 自定义分页项渲染
  const itemRender = (current, type, originalElement) => {
    if (type === 'page') {
      return (
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          width: '100%', 
          height: '100%' 
        }}>
          {current}
        </div>
      );
    }
    return originalElement;
  };

  return (
    <Spin spinning={loading}>
      <style dangerouslySetInnerHTML={{ __html: featureMappingStyles }} />
      <div className="feature-mapping-container" style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <div className="table-header-actions">
          <div>
            {/* 左侧可以放置其他信息 */}
          </div>
          <div className="action-buttons">
            <Tooltip title="自动根据名称相似度创建特征映射">
              <Button 
                icon={<ThunderboltOutlined />}
                onClick={handleAutoCreateMapping}
              >
                自动创建
              </Button>
            </Tooltip>
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              onClick={showAddModal}
            >
              手动添加
            </Button>
          </div>
        </div>
        
        <div style={{ flex: 1, overflow: 'auto' }}>
          <Table
            className={`data-table ${mappingList.length >= 10 || isMobile ? 'compact-table' : ''}`}
            dataSource={mappingList}
            columns={getColumns()}
            rowKey="id"
            pagination={false}
            rowClassName={getRowClassName}
            size={isMobile || mappingList.length >= 10 ? 'small' : 'middle'}
            bordered={true}
            scroll={{ x: isMobile ? 800 : 'max-content' }}
            tableLayout="auto"
            locale={{ emptyText: '暂无数据' }}
          />
        </div>
        
        {/* 自定义分页 */}
        <div style={customPaginationStyle} className="pagination-container">
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span>共 {pagination.total} 条，{Math.ceil(pagination.total / pageSize)} 页</span>
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Button 
              icon={<LeftOutlined />}
              onClick={goPrevPage}
              disabled={currentPage === 1}
              style={{ marginRight: '8px' }}
            />
            
            <Input
              ref={inputRef}
              style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
              value={currentPage}
              onChange={handlePageInputChange}
              onKeyPress={handlePageInputKeyPress}
            />
            
            <span style={{ margin: '0 8px' }}>/ {Math.ceil(pagination.total / pageSize)}</span>
            
            <Button 
              icon={<RightOutlined />}
              onClick={goNextPage}
              disabled={currentPage >= Math.ceil(pagination.total / pageSize)}
              style={{ marginLeft: '8px', marginRight: '8px' }}
            />
            
            <span style={{ marginLeft: '8px' }}>
              10 / 页
            </span>
          </div>
        </div>
      </div>
      
      {/* 添加特征映射模态框 */}
      <Modal
        title="添加特征映射"
        open={isModalVisible}
        onOk={handleAddMapping}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          name="feature_mapping_form"
          initialValues={{ mapping_weight: 1.0 }}
        >
          <Form.Item
            name="product_feature_id"
            label="产品特征ID"
            rules={[{ required: true, message: '请输入产品特征ID' }]}
          >
            <div className="input-with-icon">
              <div style={{ width: '100%' }}>
                <InputNumber style={{ width: '100%' }} placeholder="请输入产品特征ID" />
                <div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>
                  {getSelectedProductFeatureName() ? `已选: ${getSelectedProductFeatureName()}` : ''}
                </div>
              </div>
              <SearchOutlined 
                className="feature-select-icon" 
                onClick={showProductFeatureModal}
                title="选择产品特征"
              />
            </div>
          </Form.Item>
          
          <Form.Item
            name="template_feature_id"
            label="模板特征ID"
            rules={[{ required: true, message: '请输入模板特征ID' }]}
          >
            <div className="input-with-icon">
              <div style={{ width: '100%' }}>
                <InputNumber style={{ width: '100%' }} placeholder="请输入模板特征ID" />
                <div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>
                  {getSelectedTemplateFeatureName() ? `已选: ${getSelectedTemplateFeatureName()}` : ''}
                </div>
              </div>
              <SearchOutlined 
                className="feature-select-icon" 
                onClick={showTemplateFeatureModal}
                title="选择模板特征"
              />
            </div>
          </Form.Item>
          
          <Form.Item
            name="mapping_weight"
            label="映射权重"
            rules={[{ required: true, message: '请输入映射权重' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              min={0}
              max={1}
              step={0.1}
              placeholder="请输入映射权重 (0-1)"
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 产品特征选择模态框 */}
      <Modal
        title="选择产品特征"
        open={isProductFeatureModalVisible}
        onCancel={() => setIsProductFeatureModalVisible(false)}
        footer={null}
        width={700}
      >
        <Spin spinning={productFeatureLoading}>
          <Input
            placeholder="搜索特征 (ID, 名称, 描述)"
            value={productSearchText}
            onChange={handleProductFeatureSearch}
            style={{ marginBottom: 16 }}
            suffix={<SearchOutlined />}
            allowClear
          />
          <Table
            columns={productFeatureColumns}
            dataSource={filteredProductFeatures}
            rowKey="id"
            pagination={{ 
              pageSize: 8,
              showSizeChanger: false,
              showQuickJumper: false,
              showTotal: (total) => `共 ${total} 条`,
              size: "small",
              className: "feature-pagination",
              itemRender: itemRender
            }}
            size="small"
            onRow={(record) => ({
              onClick: () => handleProductFeatureSelect(record),
              className: 'feature-row'
            })}
          />
        </Spin>
      </Modal>

      {/* 模板特征选择模态框 */}
      <Modal
        title="选择模板特征"
        open={isTemplateFeatureModalVisible}
        onCancel={() => setIsTemplateFeatureModalVisible(false)}
        footer={null}
        width={700}
      >
        <Spin spinning={templateFeatureLoading}>
          <Input
            placeholder="搜索特征 (ID, 名称, 描述)"
            value={templateSearchText}
            onChange={handleTemplateFeatureSearch}
            style={{ marginBottom: 16 }}
            suffix={<SearchOutlined />}
            allowClear
          />
          <Table
            columns={templateFeatureColumns}
            dataSource={filteredTemplateFeatures}
            rowKey="id"
            pagination={{ 
              pageSize: 8,
              showSizeChanger: false,
              showQuickJumper: false,
              showTotal: (total) => `共 ${total} 条`,
              size: "small",
              className: "feature-pagination",
              itemRender: itemRender
            }}
            size="small"
            onRow={(record) => ({
              onClick: () => handleTemplateFeatureSelect(record),
              className: 'feature-row'
            })}
          />
        </Spin>
      </Modal>

      {/* 编辑特征映射模态框 */}
      <Modal
        title="修改映射权重"
        open={isEditModalVisible}
        onOk={handleEditMapping}
        onCancel={handleEditCancel}
        okText="确认"
        cancelText="取消"
      >
        {currentEditMapping && (
          <Form
            form={editForm}
            layout="vertical"
            name="edit_mapping_form"
          >
            <div style={{ marginBottom: '16px' }}>
              <div style={{ display: 'flex', marginBottom: '8px' }}>
                <span style={{ width: '120px', color: '#666', textAlign: 'right', marginRight: '16px' }}>产品特征名称:</span>
                <span>{currentEditMapping.product_feature_name || '-'}</span>
              </div>
              <div style={{ display: 'flex', marginBottom: '8px' }}>
                <span style={{ width: '120px', color: '#666', textAlign: 'right', marginRight: '16px' }}>模板特征名称:</span>
                <span>{currentEditMapping.template_feature_name || '-'}</span>
              </div>
            </div>
            
            <Form.Item
              name="mapping_weight"
              label="映射权重"
              rules={[{ required: true, message: '请输入映射权重' }]}
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                max={1}
                step={0.1}
                placeholder="请输入映射权重 (0-1)"
              />
            </Form.Item>
          </Form>
        )}
      </Modal>
    </Spin>
  );
};

export default FeatureMapping; 